package com.demo.config.router;

import com.sun.net.httpserver.HttpExchange;

import java.util.HashMap;
import java.util.Map;

public class RouteRegistry {
  private final Map<String, Map<String, RouteHandler>> routes = new HashMap<>();

  public void register(String method, String path, RouteHandler handler) {
    routes.computeIfAbsent(method, k -> new HashMap<>()).put(path, handler);
  }

  public RouteHandler findHandler(HttpExchange exchange) {
    String method = exchange.getRequestMethod();
    String path = exchange.getRequestURI().getPath();

    Map<String, RouteHandler> methodRoutes = routes.get(method);
    if (methodRoutes == null) {
      return null;
    }

    // 精确匹配
    RouteHandler handler = methodRoutes.get(path);
    if (handler != null) {
      return handler;
    }

    // 通配符匹配 (可选)
    for (Map.Entry<String, RouteHandler> entry : methodRoutes.entrySet()) {
      if (path.matches(entry.getKey().replace("*", ".*"))) {
        return entry.getValue();
      }
    }

    return null;
  }
}
